package com.zx.map.service.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.zx.map.dao.AgentInfoDao;
import com.zx.map.dao.MerchantCertificateInfoDao;
import com.zx.map.dao.MerchantInfoDao;
import com.zx.map.dao.OrdLogDao;
import com.zx.map.dao.mapper.MerchantInfoMapper;
import com.zx.map.dao.model.AgentInfo;
import com.zx.map.dao.model.MerchantCertificateInfo;
import com.zx.map.dao.model.MerchantCertificateInfoExample;
import com.zx.map.dao.model.MerchantInfo;
import com.zx.map.dao.model.MerchantInfoExample;
import com.zx.map.dao.model.OrdLogExample;
import com.zx.map.dao.model.StoreInfo;
import com.zx.map.dao.model.TerminalInfoExample;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.BaseAcctInfoService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.SettleCardInfoService;
import com.zx.map.service.StoreInfoService;
import com.zx.map.service.domain.MerchantInfoDomain;
import com.zx.map.service.domain.agent.TransAgentDomain;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.BaseAcctInfoModel;
import com.zx.map.service.model.MerchantInfoDetailModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.MerchantInfoTodoTask;
import com.zx.map.service.model.SettleCardInfoModel;
import com.zx.map.service.model.TerminalInfoModel;
import com.zx.map.service.model.TodoTaskModel;
import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.MyBeanUtils;
import com.zx.map.utils.SUConstants;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;

/**
 * Created by IntelliJ IDEA. User: Administrator Date: 14-12-10 Time: 涓嬪崍9:10 To
 * change this template use File | Settings | File Templates.
 */
@Component("MerchantInfoService")
public class MerchantInfoServiceImpl implements MerchantInfoService {

	@Autowired
	private MerchantInfoMapper merchantInfoMapper;

	@Autowired
	private MerchantInfoDao dao;
	@Autowired
	private SettleCardInfoService settleCardInfoService;

	@Autowired
	private MerchantCertificateInfoDao merchantCertificateInfoDao;
	@Autowired
	private AgentInfoDao agentInfoDao;
	@Autowired
	private BaseAcctInfoService baseAcctInfoService;

	@Autowired
	private AgentInfoService agentInfoService;

	@Autowired
	private OrdLogDao ordLogDao;
	@Autowired
	private StoreInfoService storeInfoService;
	/**
	 * 验证用户注册 手机号 是否存在
	 *
	 * @param telephone
	 * @return
	 */
	public boolean checkMerchantExistByTelephone(String telephone) {
		if (StringUtils.isNotBlank(telephone)) {
			MerchantInfoModel phoneCheck = new MerchantInfoModel();
			phoneCheck.setSysAccount(telephone);
			List<MerchantInfoModel> phoneList = getListByModel(phoneCheck);
			if (null != phoneList && phoneList.size() >= 1) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 验证用户注册 手机号 证件号是否存在
	 *
	 * @param identityNo
	 * @return
	 */
	public boolean checkMerchantByIdentityNo(String identityNo) {
		if (StringUtils.isNotBlank(identityNo)) {
			MerchantInfoModel identityCheck = new MerchantInfoModel();
			identityCheck.setLegalIdentityno(identityNo);
			List<MerchantInfoModel> identityList = getListByModel(identityCheck);
			if (null != identityList && identityList.size() >= 1) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 改门店是否认证过
	 * @param merchantId
	 * @return
	 */
	public boolean checkStoreInfoByMerchantId(String merchantId) {
		StoreInfo storeInfo = storeInfoService.find(merchantId);
		if(Objects.nonNull(storeInfo)) {
			return true;
		}
		return false;
	}
	/**
	 * 得到所有数据列表
	 */
	public List<MerchantInfoModel> getAllList() throws DataAccessException {
		List<MerchantInfo> list = dao.getListByExample(null);
		List<MerchantInfoModel> modelList = MyBeanUtils.map(list, MerchantInfoModel.class);
		return modelList;
	}

	/**
	 * 商户号 = key 根据单Key查找Model
	 */
	public MerchantInfoModel getModelByKey(String key) throws DataAccessException {
		Assert.isTrue(StringUtils.isNotBlank(key));
		MerchantInfo o = dao.selectByPrimaryKey(key);
		MerchantInfoModel model = new MerchantInfoModel();
		if (o != null) {
			MyBeanUtils.copyProperties(o, model);
		}

		return model;
	}

	/**
	 * 根据Model查找列表
	 */
	public List<MerchantInfoModel> getListByModel(MerchantInfoModel model) throws DataAccessException {
		MerchantInfoExample example = initMerchantExample(null, model);
		List<MerchantInfo> list = dao.getListByExample(example);
		List<MerchantInfoModel> modelList = MyBeanUtils.map(list, MerchantInfoModel.class);
		return modelList;
	}

	/**
	 * 新增 base_acct_info 在新增商户 新增代理的时候要记录一条
	 */
	public String add(MerchantInfoModel model) throws DataAccessException, UnsupportedEncodingException {
		MerchantInfo temp = new MerchantInfo();
		MyBeanUtils.copyProperties(model, temp);
		String key = dao.add(temp);
		BaseAcctInfoModel baseAcctInfoModel = new BaseAcctInfoModel();
		baseAcctInfoModel.setCustId(key);// 设置成主键一致，从而保持关联
		baseAcctInfoModel.setCustType("1");
		baseAcctInfoModel.setAcctStatus("N");
		baseAcctInfoModel.setAcctType("B");
		baseAcctInfoModel.setAcctBal(0.00);
		baseAcctInfoModel.setAvlBal(0.00);
		baseAcctInfoModel.setFrzBal(0.00);
		baseAcctInfoModel.setCreateDate(new Date());

		baseAcctInfoService.add(baseAcctInfoModel);
		return key;
	}

	/**
	 * 修改
	 */
	public String update(MerchantInfoModel model) throws DataAccessException {
		Assert.isTrue(StringUtils.isNotBlank(model.getMerchantId()));
		MerchantInfo temp = new MerchantInfo();
		MyBeanUtils.copyProperties(model, temp);
		dao.update(temp);
		return model.getMerchantId();
	}

	/**
	 * 删除
	 */
	public void delete(MerchantInfoModel model) throws DataAccessException {
		Assert.isTrue(StringUtils.isNotBlank(model.getMerchantId()));
		MerchantInfo temp = new MerchantInfo();
		MyBeanUtils.copyProperties(model, temp);
		dao.delete(temp);
	}

	/**
	 * 分页查询 当前登陆代理商发展的用户
	 *
	 * @return
	 * @throws DataAccessException
	 */
	public Map getPageByDomain(MerchantInfoDomain domain, AgentInfoModel curAgentInfoModel) throws DataAccessException {
		if (curAgentInfoModel != null) {
			curAgentInfoModel.setHasSelf(true);
		}
		Map<String, Object> resultMap = new HashedMap();

		MerchantInfoModel merchantInfoModel = new MerchantInfoModel();
		MyBeanUtils.copyProperties(domain, merchantInfoModel);
		AgentInfoModel agentInfoModel = new AgentInfoModel();
		agentInfoModel.setAgentName(domain.getAgentName());
		MerchantInfoExample example = initMerchantExample(curAgentInfoModel, agentInfoModel, merchantInfoModel);
		int pageBegin = (domain.getPageNum() - 1) * domain.getPageSize();
		List<MerchantInfo> list = dao.getPageByExample(domain.getPageSize(), pageBegin, example);

		List<MerchantInfoModel> merchantInfoModelList = new ArrayList<MerchantInfoModel>();
		for (MerchantInfo o : list) {
			MerchantInfoModel temp = new MerchantInfoModel();
			MyBeanUtils.copyProperties(o, temp);
			// 获得结算信息
			SettleCardInfoModel cardParam = new SettleCardInfoModel();
			cardParam.setSubjectId(o.getMerchantId());
			List<SettleCardInfoModel> list3 = settleCardInfoService.getListByModel(cardParam);
			if (list3.size() > 0) {
				SettleCardInfoModel scm = list3.get(0);
				temp.setDepositBank(scm.getDepositBank());
				temp.setSettleId(scm.getSettleId());
			}
			merchantInfoModelList.add(temp);
		}
		int count = dao.countByExample(example);
		resultMap.put("count", count);
		resultMap.put("list", merchantInfoModelList);
		return resultMap;
	}

	/**
	 * 新增商户终端关联表
	 */
	public void addMerchantTerminalInfo(String merchantId, String terminalId) throws DataAccessException {
		dao.addMerchantTerminalInfo(merchantId, terminalId);

	}

	/**
	 * 新增商户证件信息关联表
	 *
	 * @throws DataAccessException
	 */
	public void addMerchantCertificateInfo(MerchantCertificateInfo record) throws DataAccessException {
		// 查找是否存在，如果存在，则更新相关信息edit by wenjw 2016.9.28
		MerchantCertificateInfo existInfo = dao.getMerchantCertificateInfo(record.getMerchantId());
		if (existInfo == null) {
			dao.addMerchantCertificateInfo(record);
		} else {
			dao.updateMerchantCertificateInfo(record);
		}
	}

	public void updateMerchantCertificateInfo(MerchantCertificateInfo record) throws DataAccessException {
		dao.updateMerchantCertificateInfo(record);
	}

	public MerchantCertificateInfo getMerchantCertificateInfoByMerchantId(String merchantId)
			throws DataAccessException {
		return dao.getMerchantCertificateInfo(merchantId);
	}

	/**
	 * 获得客商，证件，结算信息
	 *
	 * @param key
	 * @return MerchantInfoDetailModel
	 * @throws DataAccessException
	 * @author baojun.liu
	 */
	@Override
	public MerchantInfoTodoTask transformMerchantDetailToTask(String key) throws DataAccessException {
		MerchantInfoTodoTask merchantInfoTodoTask = new MerchantInfoTodoTask();
		MerchantInfoModel o = this.getModelByKey(key);
		merchantInfoTodoTask.setMerchantInfoModel(o);
		// 并且设置detail中代理商编号及账号
		// 获得证件信息
		MerchantCertificateInfoExample example = new MerchantCertificateInfoExample();
		MerchantCertificateInfoExample.Criteria criteria = example.createCriteria();

		if (StringUtils.isNotBlank(o.getMerchantId())) {
			criteria.andMerchantIdEqualTo(o.getMerchantId());
		}
		List<MerchantCertificateInfo> list = this.merchantCertificateInfoDao.getListByExample(example);
		if (list != null && list.size() > 0) {
			merchantInfoTodoTask.setMerchantCertificateInfo(list.get(0));
		}

		// 获得结算信息
		SettleCardInfoModel cardParam = new SettleCardInfoModel();
		cardParam.setSubjectId(o.getMerchantId());
		List<SettleCardInfoModel> list1 = settleCardInfoService.getListByModel(cardParam);
		if (list1 != null && list1.size() > 0) {
			merchantInfoTodoTask.setSettleCardInfoModel(list1.get(0));
		}

		merchantInfoTodoTask.setTodoTaskModel(new TodoTaskModel());
		return merchantInfoTodoTask;
	}

	/**
	 * 获得客商，证件，结算信息
	 *
	 * @param key
	 * @return MerchantInfoDetailModel
	 * @throws DataAccessException
	 * @author baojun.liu
	 */
	@Override
	public MerchantInfoDetailModel getMerchantDetail(String key) throws DataAccessException {
		MerchantInfo o = dao.selectByPrimaryKey(key);
		AgentInfo agentInfo = agentInfoDao.selectByPrimaryKey(o.getAgentId());
		MerchantInfoDetailModel model = new MerchantInfoDetailModel();
		MyBeanUtils.copyProperties(o, model);
		model.setAgentSysAccount(agentInfo.getSysAccount());// 查询代理商信息
		// 并且设置detail中代理商编号及账号
		// 获得证件信息
		MerchantCertificateInfoExample example = new MerchantCertificateInfoExample();
		MerchantCertificateInfoExample.Criteria criteria = example.createCriteria();

		if (StringUtils.isNotBlank(o.getMerchantId())) {
			criteria.andMerchantIdEqualTo(o.getMerchantId());
		}
		List<MerchantCertificateInfo> list = this.merchantCertificateInfoDao.getListByExample(example);
		if (list != null && list.size() > 0) {
			model.setHoldIndentityCard(list.get(0).getHoldIndentityCard());
			model.setLegalIndentityImg(list.get(0).getLegalIndentityImg());
		}
		// 获得结算信息
		SettleCardInfoModel cardParam = new SettleCardInfoModel();
		cardParam.setSubjectId(o.getMerchantId());
		List<SettleCardInfoModel> list1 = settleCardInfoService.getListByModel(cardParam);
		SettleCardInfoModel smdol = new SettleCardInfoModel();
		if (list1 != null && list1.size() > 0) {
			MyBeanUtils.copyProperties(list1.get(0), smdol);
		}
		model.setSettleCardInfoModel(smdol);

		// 终端信息 提供每个用户一个终端
		TerminalInfoExample terminalInfoExample = new TerminalInfoExample();
		TerminalInfoExample.Criteria terminalInfoExampleCriteria = terminalInfoExample.createCriteria();
		if (StringUtils.isNotBlank(o.getMerchantId())) {
			terminalInfoExampleCriteria.andBelongtoMerchantidEqualTo(o.getMerchantId());
		}

		return model;
	}

	/**
	 * 根据商户获得绑定的终端
	 */
	@Override
	public List<TerminalInfoModel> getTerminalListByMerchantId(String merchantId) throws DataAccessException {
		List<TerminalInfoModel> tList = new ArrayList();
		return tList;
	}

	/**
	 * 根据登录名查找对应的代理商
	 */
	@Override
	public MerchantInfoModel getMerchantInfoModelBySysAccount(String sysAccount) throws DataAccessException {

		MerchantInfoExample example = new MerchantInfoExample();
		com.zx.map.dao.model.MerchantInfoExample.Criteria criteria = example.createCriteria();
		criteria.andSysAccountEqualTo(sysAccount);
		List<MerchantInfo> list = dao.getListByExample(example);
		if (list != null && list.size() > 0) {
			MerchantInfoModel model = new MerchantInfoModel();
			MyBeanUtils.copyProperties(list.get(0), model);
			return model;
		}
		return null;

	}

	/**
	 * 直接修改客商相关信息
	 *
	 * @throws UnsupportedEncodingException
	 */
	@Override
	public MerchantInfoModel saveDetail(MerchantInfoDetailModel detail)
			throws DataAccessException, UnsupportedEncodingException {
		// 客户信息表
		MerchantInfoModel merchantInfoModel = this.getModelByKey(detail.getMerchantId());
		MyBeanUtils.copyProperties(detail, merchantInfoModel);
		merchantInfoModel.setUpdateDate(new Date());
		String merchantId = null;
		merchantId = merchantInfoModel.getMerchantId();
		// merchantInfoModel.setStatus("0");//0--表示用户状态正常 修改的时候参照之前状态 x
		this.update(merchantInfoModel);

		// 商户证件信息关联表
		MerchantCertificateInfo record = this.getMerchantCertificateInfoByMerchantId(detail.getMerchantId());
		if (record == null) {
			record = new MerchantCertificateInfo();
			record.setMerchantId(merchantId);
			MyBeanUtils.copyProperties(detail, record);
			this.addMerchantCertificateInfo(record);
		} else {
			record.setMerchantId(merchantId);
			if (detail.getLegalIndentityImg() != "" && detail.getLegalIndentityImg() != null) {
				record.setLegalIndentityImg(detail.getLegalIndentityImg());
			}
			if (detail.getLegalOppindentityImg() != "" && detail.getLegalOppindentityImg() != null) {
				record.setLegalOppindentityImg(detail.getLegalOppindentityImg());
			}
			if (detail.getBussinessImg() != "" && detail.getBussinessImg() != null) {
				record.setBussinessImg(detail.getBussinessImg());
			}
			if (detail.getOrgcodeImg() != "" && detail.getOrgcodeImg() != null) {
				record.setOrgcodeImg(detail.getOrgcodeImg());
			}
			if (detail.getTaxImg() != "" && detail.getTaxImg() != null) {
				record.setTaxImg(detail.getTaxImg());
			}
			if (detail.getBankLicenseImg() != "" && detail.getBankLicenseImg() != null) {
				record.setBankLicenseImg(detail.getBankLicenseImg());
			}
			if (detail.getSettleCardImg() != "" && detail.getSettleCardImg() != null) {
				record.setSettleCardImg(detail.getSettleCardImg());
			}
			if (detail.getBussinessEnvImg() != "" && detail.getBussinessEnvImg() != null) {
				record.setBussinessEnvImg(detail.getBussinessEnvImg());
			}
			if (detail.getHoldIndentityCard() != "" && detail.getHoldIndentityCard() != null) {
				record.setHoldIndentityCard(detail.getHoldIndentityCard());
			}
			if (detail.getCreditCardImg() != "" && detail.getCreditCardImg() != null) {
				record.setCreditCardImg(detail.getCreditCardImg());
			}
			this.updateMerchantCertificateInfo(record);
		}

		// 结算信息表
		SettleCardInfoModel settleCardInfoModel = detail.getSettleCardInfoModel();
		settleCardInfoModel.setSubjectId(merchantId);
		settleCardInfoModel.setSubjectType("1");// 主体为商户
		if (settleCardInfoModel.getSettleId() == null) {
			// 新增结算信息表
			settleCardInfoService.add(settleCardInfoModel);
		} else {
			// 修改结算信息表
			settleCardInfoService.update(settleCardInfoModel);
		}

		return null;
	}

	/**
	 * 查询符合条件的所有merchantIdList 集合
	 */
	@Override
	public List<String> queryListMerchantIdByAgentInfo(AgentInfoModel curAgentInfoModel,
			MerchantInfoModel merchantInfoModel) {
		List<String> merchantIdList = queryMerchantIdListByAgentInfo(curAgentInfoModel, merchantInfoModel);
		return merchantIdList;
	}

	// 查找所有符合条件的 MerchantId
	@Override
	public List<String> queryMerchantIdListByAgentInfo(AgentInfoModel curAgentInfoModel,
			MerchantInfoModel merchantInfoModel) {
		MerchantInfoExample example = initMerchantExample(curAgentInfoModel, merchantInfoModel);
		return dao.getMerchantIdList(example);
	}

	// 查找MerchantInfo
	@Override
	public List<MerchantInfo> queryListMerchantInfoByAgentInfo(AgentInfoModel curAgentInfoModel,
			MerchantInfoModel merchantInfoModel) {
		MerchantInfoExample example = initMerchantExample(curAgentInfoModel, merchantInfoModel);
		return dao.getListByExample(example);
	}

	/**
	 * 查找指定条件的merchantId 集合
	 */
	public List<String> queryListMerchantIdByMerchantName(MerchantInfoModel merchantInfoModel) {
		List<String> ids = queryListMerchantInfoByMerchantName(merchantInfoModel);
		return ids;
	}

	/**
	 * 根据指定条件查找所有商户
	 */
	public List<String> queryListMerchantInfoByMerchantName(MerchantInfoModel merchantInfoModel) {
		MerchantInfoExample example = merchantExample(merchantInfoModel);
		// return dao.getListByExample(example);
		return dao.getMerchantIdList(example);
	}

	@Override
	public List<MerchantInfoModel> queryListMerchantInfoModelByAgentInfo(AgentInfoModel curAgentInfoModel,
			MerchantInfoModel merchantInfoModel) {
		MerchantInfoExample example = initMerchantExample(curAgentInfoModel, merchantInfoModel);
		List<MerchantInfo> merchantInfoList = dao.getListByExample(example);
		List<MerchantInfoModel> merchantInfoModelList = MyBeanUtils.map(merchantInfoList, MerchantInfoModel.class);
		return merchantInfoModelList;
	}

	/**
	 * 查询代理商的id
	 * 
	 * @param searchMerchantInfoModel
	 * @return
	 */
	@Override
	public List<String> queryListMerchantIdByModel(MerchantInfoModel searchMerchantInfoModel) {
		MerchantInfoExample example = initMerchantExample(null, searchMerchantInfoModel);
		List<MerchantInfo> list = dao.getListByExample(example);
		List<String> merchantIdList = new ArrayList<String>();
		for (MerchantInfo merchantInfo : list) {
			merchantIdList.add(merchantInfo.getMerchantId());
		}
		return merchantIdList;
	}

	// 商户转让
	@Override
	public Map<String, Object> transMerchant(TransAgentDomain transMerchant, AgentInfoModel curAgentInfoModel) {
		// 待转让账户
		String fromAccount = transMerchant.getFromAccount();
		// 接收账户
		String toAccount = transMerchant.getToAccount();
		MerchantInfoModel fromMerchantInfo = getMerchantInfoModelBySysAccount(fromAccount);
		AgentInfoModel toAgentInfo = agentInfoService.getAgentInfoModelBySysAccount(toAccount);
		if (fromMerchantInfo == null) {
			return CommonResponseUtils.failureResponse("待转让商户不存在！");
		}
		if (toAgentInfo == null) {
			return CommonResponseUtils.failureResponse("接收代理商不存在！");
		}
		if (fromMerchantInfo.getAgentId().equals(toAgentInfo.getAgentId())) {
			return CommonResponseUtils.failureResponse("该商户属于接收代理商，不需转让！");
		}
		if (curAgentInfoModel == null || fromMerchantInfo.getAgentId().equals(curAgentInfoModel.getAgentId())) {
		} else {
			return CommonResponseUtils.failureResponse("只能转让自己的直属商户！");
		}
		fromMerchantInfo.setAgentId(toAgentInfo.getAgentId());
		update(fromMerchantInfo);

		return CommonResponseUtils.successResponse("转让成功");
	}

	/**
	 * 初始化当前登录用户 发展的下级代理 查询条件
	 *
	 * @param curAgentInfoModel
	 * @param merchantInfoModel
	 * @return
	 */
	private MerchantInfoExample initMerchantExample(AgentInfoModel curAgentInfoModel,
			MerchantInfoModel merchantInfoModel) {
		return initMerchantExample(curAgentInfoModel, new AgentInfoModel(), merchantInfoModel);
	}

	/**
	 * 初始化当前登录用户 发展的下级代理 查询条件
	 *
	 * @param curAgentInfoModel
	 * @param merchantInfoModel
	 * @return
	 */
	private MerchantInfoExample initMerchantExample(AgentInfoModel curAgentInfoModel,
			AgentInfoModel searchAgentInfoModel, MerchantInfoModel merchantInfoModel) {
		MerchantInfoExample example = new MerchantInfoExample();
		com.zx.map.dao.model.MerchantInfoExample.Criteria criteria = example.createCriteria();
		if (StrUtils.isBlank(merchantInfoModel.getAgentId())) {
			List<String> agentIdList = agentInfoService.queryDownAgentIdList(curAgentInfoModel, searchAgentInfoModel);
			if (agentIdList == null || agentIdList.size() == 0) {
				agentIdList.add("-1");
			}
			criteria.andAgentIdIn(agentIdList);
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getMerchantName())) {
			criteria.andMerchantNameLike('%' + merchantInfoModel.getMerchantName() + '%');
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getMerchantAddr())) {
			criteria.andMerchantAddrLike('%' + merchantInfoModel.getMerchantAddr() + '%');
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getSysAccount())) {
			criteria.andSysAccountLike("%" + merchantInfoModel.getSysAccount() + "%");
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getSysPassword())) {
			criteria.andSysPasswordEqualTo(merchantInfoModel.getSysPassword());
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getProductType())) {
			criteria.andProductTypeEqualTo(merchantInfoModel.getProductType());
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getLegalIdentityno())) {
			criteria.andLegalIdentitynoLike("%" + merchantInfoModel.getLegalIdentityno() + "%");
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getAgentId())) {
			criteria.andAgentIdEqualTo(merchantInfoModel.getAgentId());
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getStatus())) {
			criteria.andStatusEqualTo(merchantInfoModel.getStatus());
		}
		if (StringUtils.isNotBlank(merchantInfoModel.getBeginDate())) {
			if(StringUtils.isNotBlank(merchantInfoModel.getEndDate())) {
				criteria.andCreateDateBetween(PmpUtils.strToDate(merchantInfoModel.getBeginDate(), "yyyy-MM-dd"),
						PmpUtils.addDate(PmpUtils.strToDate(merchantInfoModel.getEndDate(), "yyyy-MM-dd"), 1));
			}else {
				criteria.andCreateDateGreaterThanOrEqualTo(PmpUtils.strToDate(merchantInfoModel.getBeginDate(), "yyyy-MM-dd"));
			}
			
		}else if(StringUtils.isNotBlank(merchantInfoModel.getEndDate())) {
			criteria.andCreateDateLessThanOrEqualTo(PmpUtils.addDate(PmpUtils.strToDate(merchantInfoModel.getEndDate(), "yyyy-MM-dd"), 1));
		}
		example.setOrderByClause("create_Date desc");
		return example;
	}

	private MerchantInfoExample merchantExample(MerchantInfoModel merchantInfoModel) {
		MerchantInfoExample example = new MerchantInfoExample();
		com.zx.map.dao.model.MerchantInfoExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(merchantInfoModel.getMerchantName())) {
			criteria.andMerchantNameLike('%' + merchantInfoModel.getMerchantName() + '%');
		}
		example.setOrderByClause("create_Date desc");
		return example;
	}

	@Override
	public List<MerchantInfo> findByName(MerchantInfoModel model) {

		MerchantInfoExample example = new MerchantInfoExample();
		com.zx.map.dao.model.MerchantInfoExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(model.getMerchantName())) {
			criteria.andMerchantNameLike('%' + model.getMerchantName() + '%');
		}
		example.setOrderByClause("create_Date desc");

		return merchantInfoMapper.getPageByModel(model.getPageSize(), model.getPageNum(), example);

	}

	@Override
	public int bind(String selfId,String bindId) {
		MerchantInfo self=merchantInfoMapper.selectByPrimaryKey(selfId);
		MerchantInfoExample example = new MerchantInfoExample();
		com.zx.map.dao.model.MerchantInfoExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(bindId)) {
			criteria.andSysAccountEqualTo(bindId);
		}
		List<MerchantInfo> list=merchantInfoMapper.selectByExample(example);
		if(list!=null && list.size()>0) {
			if( list.get(0).getDepth()<=2) {
				self.setParentMerchantId(list.get(0).getMerchantId());
			}else {
				throw new RuntimeException("仅限3级层级");
			}
			self.setParentApproved(0);
			return merchantInfoMapper.updateByPrimaryKey(self);
		}
		
		return 0;
	}

	@Override
	public List<MerchantInfo> findByParent(String parentid) {
		MerchantInfoExample example = new MerchantInfoExample();
		com.zx.map.dao.model.MerchantInfoExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(parentid)) {
			criteria.andParentIdEqual(parentid);
		}
		example.setOrderByClause("create_Date desc");
		return merchantInfoMapper.selectByExample(example);
	}
	
	@Override
	public List<MerchantInfo> getById(String id) {
		MerchantInfoExample example = new MerchantInfoExample();
		com.zx.map.dao.model.MerchantInfoExample.Criteria criteria = example.createCriteria();
		criteria.andMerchantIdEqualTo(id);
		return merchantInfoMapper.selectByExample(example);
	}

	@Override
	public int approve(String id, int approve) {
		MerchantInfo  mi =merchantInfoMapper.selectByPrimaryKey(id);
		mi.setParentApproved(approve);
		if(approve==1) {
			mi.setDepth(mi.getDepth()+1);
			mi.setJoinDate(new Date());//分店加入总店的时间
		}
		//更新父类为非叶子节点
		{
			MerchantInfo parent = merchantInfoMapper.selectByPrimaryKey(mi.getParentMerchantId());
			parent.setLeaf(1);
			merchantInfoMapper.updateByPrimaryKey(parent);
		}
		return merchantInfoMapper.updateByPrimaryKey(mi);
	}

	@Override
	public int unbind(String unbindId) {
		MerchantInfo  mi =merchantInfoMapper.selectByPrimaryKey(unbindId);
		mi.setParentMerchantId(null);
		mi.setDepth(1);
		mi.setParentApproved(0);
		return merchantInfoMapper.updateByPrimaryKey(mi);
	}
	
	@Override
	public List<MerchantInfo> getBranch(String parentId, Date date){
		
		List<MerchantInfo> list = new ArrayList<>();
		MerchantInfoExample example = new MerchantInfoExample();
		com.zx.map.dao.model.MerchantInfoExample.Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(parentId) && !Objects.isNull(date)) {
			criteria.andParentIdEqual(parentId);
			criteria.andJoinDateLessThanOrEqualTo(date);
			criteria.andParentAppovedEqual("1");
		}else {
			return list;
		}
		
		List<MerchantInfo> tmpList = merchantInfoMapper.selectByExample(example);
		
		if(!tmpList.isEmpty()) {
			
			for(MerchantInfo mi : tmpList) {
				
				if(mi.getLeaf() == 1) {
					list = getBranch(mi.getMerchantId(), date);
				}
			}
		}
		tmpList.addAll(list);
		return tmpList;
	}
	@Override
	public Map<String, Object> getBranchMoney(String parentId, String date){
		Date currentDay = new Date();
		if(StringUtils.isEmpty(date)) {
			currentDay = PmpUtils.strToDate(PmpUtils.dateToString(new Date(), "yyyy-MM-dd") + " 00:00:00", "yyyy-MM-dd 00:00:00");
		}else {
			currentDay = PmpUtils.strToDate(date + " 00:00:00", "yyyy-MM-dd 00:00:00");
		}
		
		MerchantInfo o = dao.selectByPrimaryKey(parentId);
		List<MerchantInfo> infoList = getBranch(parentId, PmpUtils.addDate(currentDay, 1));
		
		Double paymentAmt = getPaymentAmt(o, currentDay);
		
		if(!infoList.isEmpty()) {
			for(MerchantInfo mi : infoList) {
				paymentAmt += getPaymentAmt(mi, currentDay);
			}
		}
		
		Map<String, Object> result = new HashMap<>();
		result.put("paymentAmt", String.format("%.2f", paymentAmt));
		return result;
	}
	private Double getPaymentAmt(MerchantInfo merchantInfo, Date currentDay) {
		Double paymentAmt = 0.0;
		try {
			OrdLogExample example = new OrdLogExample();
			OrdLogExample.Criteria criteria = example.createCriteria();
			criteria.andMerchantIdEqualTo(merchantInfo.getMerchantId());
			criteria.andTransStatusEqualTo(SUConstants.TRANS_STATUS_S);
			if(Objects.nonNull(merchantInfo.getJoinDate()) && merchantInfo.getJoinDate().before(currentDay)) {
				criteria.andCreateDateBetween(merchantInfo.getJoinDate(), PmpUtils.addDate(currentDay, 1));
				paymentAmt = ordLogDao.getPaymentAmt(example);
			}else {
				criteria.andCreateDateLessThanOrEqualTo(PmpUtils.addDate(currentDay, 1));
				paymentAmt = ordLogDao.getPaymentAmt(example);
			}
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		 return paymentAmt;
	}
}
